
package de.dtools.n2g.core;

/**
 *	@project:	note2go
 *	@author:	D.Toepel
 *	@version:	2009-08-04
 *	@note:		---
 *	
 *	Copyright (C) 2009  D.Toepel <de.dtools> {at} <gmail> {dot} <com>
 *	
 *	This program is free software: you can redistribute it and/or modify
 *	it under the terms of the GNU General Public License as published by
 *	the Free Software Foundation, either version 3 of the License, or
 *	(at your option) any later version.
 *	
 *	This program is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *	GNU General Public License for more details.
 *	
 *	You should have received a copy of the GNU General Public License
 *	along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *	
 */

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.ContainerEvent;
import java.awt.event.ContainerListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.Timer;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import javax.swing.tree.*;

import de.dtools.n2g.note.*;
import de.dtools.n2g.note.EntrySet.TYPE;
import de.dtools.n2g.res.Resource;
import de.dtools.n2g.search.Search;
import de.dtools.n2g.sql.DBResult;
import de.dtools.n2g.sql.DBEvent;
import de.dtools.n2g.sql.Database;
import de.dtools.n2g.start.N2GLogin;


public class Note2Go extends JFrame {

	private static final long serialVersionUID = 1L;
	final static String TAGTREE = "Tags als Baumansicht";	
	final static String TAGCLOUD = "Tags als Schlagwortwolke";
	


	// *************************************************
	// Objekte fuer MainPanel
	//
	private Search home;
	private LabelTree labelTree;
	private JSplitPane jSplitPane1;
	private JPanel mainPane;
	private boolean isSearchResult = false;
	private JScrollPane jNavLeft;
	private JPanel cards;
	private JPanel jCloud;
	private static Resource res = new Resource();
	private Timer time;
	private NTimer nTimer;
	private Status statusBar = new Status();
	private JButton btnSearch;
	private Result iResult;
	private JPanel sResult;
	private JButton btnShow;
	private JPanel leftNavi;
	private Entry currentEntry = null;
	
	
	final Label root = new Label("root", -100);
	final Label common = new Label("Allgemeines", -110);
	final Label used = new Label("offene Notizen", -120);
	final Label tags = new Label("Tags / Labels", -130);
	
	final Label lHome = new Label("Startseite", -111);
	final Label lResult = new Label("Suchergebnis", -112);
	final Label lOption = new Label ("Einstellungen", -113);
	
	final Label all = new Label("Alle Labels", -131);
	final Label list = new Label("Ergebnisliste", -132);
	
	private Label[] allTagList;
	private Label[] allTagListNumbered;
	private Label[] nodes;
	private int selectedRow;
	
	
	final Label l1 = new Label("Note2Go", 1);
	final Label l2 = new Label("Beispiel", 2);
    final Label l3 = new Label("HowTo", 3);
    
	private int newNotesCounter = -1000;
	

	private JPanel pref;
	private OptionsSet options;
	private JMenuBar menuBar;
	private static Database iDB;
	
	private DBResult dbResult;
	private JMenu jSubMenu;
	protected int lastID;
	private Label currLabel;
	private boolean canSelected;
	public static void setDatabase(Database iDB) {
		Note2Go.iDB = iDB;		
	}
	public Note2Go(){
		super("Note2Go");
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setMinimumSize(new Dimension(800,600));
		this.setTitle("Note2Go");
		this.addWindowListener(new WindowListener() {
			
			
			@Override
			public void windowClosing(WindowEvent e) {
				time.cancel();
//				iDB.closeConnection();
			}
			
			@Override
			public void windowActivated(WindowEvent e) {
				nTimer = new NTimer(statusBar,0);
				time = new Timer();
				time.schedule(nTimer, 0, 1000);
			}

			@Override
			public void windowClosed(WindowEvent arg0) {}

			@Override
			public void windowDeactivated(WindowEvent arg0) {}

			@Override
			public void windowDeiconified(WindowEvent arg0) {}

			@Override
			public void windowIconified(WindowEvent arg0) {}

			@Override
			public void windowOpened(WindowEvent arg0) {}
		});
		
		initPrefs();
		
		initGUI();
		
	}
	
	private void initPrefs(){
		dbResult = iDB.getDBResult();
		options = iDB.getOptions();
		
		setAllTags();
		setStatusText();
	}
	
	private void setTitleString(String title){
		this.setTitle("Note2Go -- " + title);
	}
	
	private void setAllTags(){
		dbResult = iDB.getTagList(null);
		String[][] result = dbResult.getRowContent();
		if(result != null ){
			allTagList = new Label[result.length];
			allTagListNumbered = new Label[result.length];
			for (int i = 0; i < result.length; i++) {
				allTagList[i] = new Label(result[i][0] , Integer.parseInt(result[i][1]));
				allTagListNumbered[i] = new Label(
						result[i][0] + " (" + result[i][2] + ")", 
						Integer.parseInt(result[i][1]));
			}
		}
	}
	
	private void setStatusText() {
		String statusString = 
			"  Lokal: " + options.getLocalUser().getName() + 
			" (ID: " + options.getLocalUser().getUserID() + ")";

		if (options.getHostUser().getName().length() > 4) {
			statusString += " -- Online: " + options.getHostUser().getName()
					+ " (ID: " + options.getHostUser().getUserID() + ")";
		}
		statusBar.setStatusMessage(statusString);
	}
	
	private void initGUI(){
		try {
			this.setSize(800, 600);
			{
				jSplitPane1 = new JSplitPane();
				jSplitPane1.setOneTouchExpandable(true);
				jSplitPane1.setDividerLocation(160);				
				{
					cards = new JPanel(new CardLayout());
					{
						labelTree = getLabelTree();
						jCloud = new JPanel();

						cards.add(labelTree, TAGTREE);
						cards.add(jCloud, TAGCLOUD);
					}
					leftNavi = new JPanel(new BorderLayout());
					{
						leftNavi.add(cards, BorderLayout.CENTER);
					}
					jNavLeft = new JScrollPane(leftNavi);
					jNavLeft.setBorder(BorderFactory.createEmptyBorder(0,0,0,0));
					jNavLeft.setMinimumSize(new Dimension(80,100));
				}
				{
					mainPane = new JPanel(new CardLayout());
					mainPane.setMinimumSize(new Dimension(600,100));
					{
						
						home = new Search();
						{
							btnSearch = new JButton();
							btnSearch.addActionListener(new ActionListener() {
								public void actionPerformed(ActionEvent evt) {
				            		setSearchResult();
								}
				    		});
						}
						home.setSearchButton(btnSearch);
						home.setBorder(BorderFactory.createEmptyBorder(5,10,5,10));
						mainPane.add(home, "card-111");
						showCard(-111);
					}
					jSplitPane1.add(jNavLeft, JSplitPane.LEFT);
					jSplitPane1.add(mainPane, JSplitPane.RIGHT);
					
				}
			}
			
			this.getContentPane().add(getN2GMenuBar(), BorderLayout.PAGE_START);
			this.getContentPane().add(jSplitPane1, BorderLayout.CENTER);
			this.getContentPane().add(statusBar, BorderLayout.PAGE_END);
			
		} catch (Exception e) {}
	}
	
	private void showCard(int cardID){
		CardLayout cl = (CardLayout)(mainPane.getLayout());
		cl.show(mainPane, "card"+cardID);
	}
	
	private LabelTree getLabelTree(){
		if(labelTree == null){
			
	        
	        Label.linkLabels(root, new Label[] {common, used , tags});
	        Label.linkLabels(common, new Label[] {lHome, lResult});
	        Label.linkLabels(tags, new Label[] {all, list});
	        Label.linkAllLabels(all, allTagListNumbered);

	        labelTree = new LabelTree(root);
	        labelTree.setEditable(true);
			labelTree.addTreeSelectionListener(new TreeSelectionListener() {

				@Override
				public void valueChanged(TreeSelectionEvent e) {
					if(!canSelected){
						canSelected = true;
						return;
					}
					
					TreePath path = labelTree.getSelectionModel().getSelectionPath();
					if (path != null) {
//						for (int i = 0; i < path.getPathCount(); i++) {
//							label = (Label) path.getPathComponent(i);
//						}
					}
					currLabel = (Label) labelTree.getLastSelectedPathComponent();
					
					if (currLabel == null) return;					
					
					if (currLabel.isLeaf()) {
						try {
							if(currLabel.getToolTip() != null){
								setTitleString(currLabel.getToolTip());
							}else{
								setTitleString(currLabel.getName());
							}
							if(currLabel.isNote() || currLabel.getLabelID() < -1){
								showCard(currLabel.getLabelID());
								if(!currLabel.isNote()){
									currentEntry = null;
								}
							}else{
								currentEntry = null;
							}
						} catch (Exception e2) {}
						
						if(path.getPathCount() > 2){
							Label node = (Label)path.getPathComponent(2); 
							if (node.getLabelID() == -131 && !node.isLeaf()){
								// get searchresult from all labels
								selectedRow = labelTree.getRowForPath(path) + 1;
								setSQLRequest(new Label[]{(Label)path.getPathComponent(3)});
								
							}else if (node.getLabelID() == -132 && !node.isLeaf()){
								Label[] nodeLabels = new Label[path.getPathCount()-3];
								for (int i = 3; i < path.getPathCount(); i++) {
									nodeLabels[i - 3] = (Label) path.getPathComponent(i);
								}
								selectedRow = labelTree.getRowForPath(path);
								setSQLRequest(nodeLabels);
								
							}
						}
					}
				}
			});
		}
		
		labelTree.select(lHome);
		return labelTree;
	}
	
	private void setSQLRequest(Label[] labels){
		// get note headers
		dbResult = iDB.getEntryHeaders(labels);
		setSearchTable();
		
		nodes = new Label[labels.length + 1];
		nodes[0] = list;
		for (int i = 1; i <= labels.length; i++) {
			nodes[i] = new Label(labels[i-1].getName(), labels[i-1].getLabelID());
		}
		
		// get labels
		dbResult = iDB.getTagList(labels);
		
		String[][] result = dbResult.getRowContent();
		
		Label[] leafs = new Label[result.length];
		for (int i = 0; i < result.length; i++) {
			leafs[i] = new Label(result[i][1], Integer.parseInt(result[i][0]));
		}
		((LabelModel) labelTree.getModel()).removeAllChildren(list);
		((LabelModel) labelTree.getModel()).addResultChildren(nodes, leafs);
		canSelected = false;
		labelTree.select(nodes[nodes.length - 1]);
		nodes = null;
	}
	
	private void setSearchResult(){
		String q = home.getSearchText();
		dbResult = iDB.getSearchResult(q);
		
		setSearchTable();
		labelTree.select(lResult);
	}
	
	
	private void setSearchTable(){
		if(sResult == null){
			sResult = new JPanel(new BorderLayout());
		}

		String[] header = new String[]{"ID","Titel","Datum"};
		final JTable jt = new JTable(dbResult.getRowContent(),header);
//		
		jt.getTableHeader().getColumnModel().getColumn(0).setMaxWidth(80);
		jt.getTableHeader().getColumnModel().getColumn(0).setMinWidth(40);
		jt.getTableHeader().getColumnModel().getColumn(2).setMaxWidth(180);
		jt.getTableHeader().getColumnModel().getColumn(2).setMinWidth(170);
		jt.setFillsViewportHeight(true);
		jt.setAutoCreateRowSorter(true);
		
		
		jt.setShowGrid(true);
		ListSelectionModel lsm = jt.getSelectionModel();
		lsm.addListSelectionListener(new ListSelectionListener() {
			
			@Override
			public void valueChanged(ListSelectionEvent arg0) {
				int iRow = jt.getSelectionModel().getLeadSelectionIndex();
				int id = Integer.parseInt(jt.getModel().getValueAt(iRow, 0).toString());
				if(lastID != id){
					setEntryDetail(id);
					lastID = id;
				}
			}
		});

		sResult.removeAll();
		sResult.add(new JScrollPane (jt), BorderLayout.CENTER);
		if (!isSearchResult){
			mainPane.add(sResult, "card-112");
			isSearchResult = true;
		}
		showCard(-112);
		

	}

	
	private Entry setEntryDetail(int entryID){
		final Entry ed;
		EntrySet es;
		if ((int)entryID < 1){
			
			es = new EntrySet(true);
			es.setEntryAutor(options.getAuthor());
			ed = new Entry(es);
			newNotesCounter--;
			mainPane.add(ed, "card" + (newNotesCounter));
			showCard(newNotesCounter);
			
			Label newNote = new Label(
					"Neue Notiz ("+ (Math.abs(newNotesCounter + 1000)) +")",
					newNotesCounter);
			((LabelModel) labelTree.getModel()).addChild(used,newNote);
			newNote.setToolTip("neue Notiz, bitte speichern");
			newNote.isNote(true);
			newNote.isNewNote(true);
			ed.showDetails();
			labelTree.select(newNote);
			
		}
		else{
			es = iDB.getEntry(entryID);;
			ed = new Entry(es);
			
			mainPane.add(ed, "card"+entryID);
			showCard(entryID);
			
			Label newNote = new Label(es.getEntryTitle(),entryID);
			((LabelModel) labelTree.getModel()).addChild(used,newNote);
			newNote.setToolTip(es.getEntryTitle());
			newNote.isNote(true);
			labelTree.select(newNote);
		}
		ed.setCommonLabelList(allTagList);
		ed.setPreferredSize(new java.awt.Dimension(600, 460));
		ed.addEditorEventListener(new EntryEvents() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void buttonSave_Clicked(ActionEvent evt) {
				saveNote();
				
			}
			
			@Override
			public void buttonRefresh_Clicked(ActionEvent evt) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void buttonOptions_Clicked(ActionEvent evt) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void buttonDelete_Clicked(ActionEvent evt) {
				deleteNote();
			}
		});
		ed.addComponentListener(new ComponentListener() {

			@Override
			public void componentShown(ComponentEvent e) {
				currentEntry = (Entry)e.getSource();
			}
			
			@Override
			public void componentResized(ComponentEvent e) {}
			
			@Override
			public void componentMoved(ComponentEvent e) {}
			
			@Override
			public void componentHidden(ComponentEvent e) {}
		});
		
		return ed;
	}
	
	private JMenuBar getN2GMenuBar(){
		if(menuBar == null) {
			menuBar = new JMenuBar();
			JMenu jMenu, jSubMenu;
			JMenuItem jMenuItem;
			{
				jMenu = new JMenu("Notiz");
				{
					jMenuItem = new JMenuItem("Neue Notiz");
					jMenuItem.setIcon(res.getLabelNewNote);
					jMenuItem.setAccelerator(KeyStroke.getKeyStroke(
				            KeyEvent.VK_N, ActionEvent.CTRL_MASK));
					jMenuItem.addActionListener(new ActionListener() {
			        	public void actionPerformed(ActionEvent evt) {
			        		setEntryDetail(0);
			        	}
			        });
					jMenu.add(jMenuItem);
				    
					jMenuItem = new JMenuItem("Speichern");
					jMenuItem.setIcon(res.saveIcon);
					jMenuItem.setAccelerator(KeyStroke.getKeyStroke(
				            KeyEvent.VK_S, ActionEvent.CTRL_MASK));
					jMenuItem.addActionListener(new ActionListener() {
			        	public void actionPerformed(ActionEvent evt) {
			        		saveNote();
				        }
				    });		    
				    jMenu.add(jMenuItem);
				    
				    jMenuItem = new JMenuItem("Schliessen");
					jMenuItem.setIcon(res.getCloseNoteIcon());
					jMenuItem.setAccelerator(KeyStroke.getKeyStroke(
				            KeyEvent.VK_W, ActionEvent.CTRL_MASK));
					jMenuItem.addActionListener(new ActionListener() {
			        	public void actionPerformed(ActionEvent evt) {
			        		closeNote();
				        }
				    });		    
				    jMenu.add(jMenuItem);
				    
				    jMenu.addSeparator();
				    
				    jMenuItem = new JMenuItem("Loeschen");
					jMenuItem.setIcon(res.deleteIcon);
					jMenuItem.addActionListener(new ActionListener() {
			        	public void actionPerformed(ActionEvent evt) {
			        		deleteNote();
				        }
				    });		    
				    jMenu.add(jMenuItem);
				    
				    jMenu.addSeparator();
				    
				    jMenuItem = new JMenuItem("Exportieren");
				    jMenuItem.setIcon(res.getExportIcon());
				    jMenuItem.addActionListener(new ActionListener() {
						
						@Override
						public void actionPerformed(ActionEvent arg0) {
							if(currentEntry != null){
								currentEntry.exportStyledDocument();
							}else{
								JOptionPane.showMessageDialog(new JFrame(),
										"Keine Notiz ausgewaehlt!", 
										"Hinweis",
										JOptionPane.INFORMATION_MESSAGE);
							}
						}
					});
					jMenu.add(jMenuItem);
					
					jMenuItem = new JMenuItem("Importieren");
					jMenuItem.setIcon(res.getImportIcon());
					jMenuItem.addActionListener(new ActionListener() {
						
						@Override
						public void actionPerformed(ActionEvent arg0) {
							currentEntry = setEntryDetail(0);
							if(currentEntry != null){
								currentEntry.importStyledDocument();
							}
						}
					});
					jMenu.add(jMenuItem);
					
					jMenu.addSeparator();
				    
				    jMenuItem = new JMenuItem("Beenden");
				    jMenuItem.setIcon(res.getCloseIcon());
				    jMenuItem.addActionListener(new ActionListener() {
						@Override
						public void actionPerformed(ActionEvent arg0) {
							//TODO dialog save before quit
							
							System.exit(0);
						}
					});
					jMenu.add(jMenuItem);
				}
				menuBar.add(jMenu);
			}
			{
				jMenu = new JMenu("Bearbeiten");
				{
					jMenuItem = new JMenuItem("zurueck");
					jMenuItem.setIcon(res.undoIcon);
					jMenuItem.setAccelerator(KeyStroke.getKeyStroke(
				            KeyEvent.VK_Z, ActionEvent.CTRL_MASK));
					jMenuItem.addActionListener(new ActionListener() {
						@Override
						public void actionPerformed(ActionEvent arg0) {
							if(currentEntry != null){
								currentEntry.noteUndoAction();
							}else{
								JOptionPane.showMessageDialog(new JFrame(),
										"Keine Notiz ausgewaehlt!", 
										"Hinweis",
										JOptionPane.INFORMATION_MESSAGE);
							}
						}
					});
					jMenu.add(jMenuItem);
					
					jMenuItem = new JMenuItem("vorwaerts");
					jMenuItem.setIcon(res.redoIcon);
					jMenuItem.setAccelerator(KeyStroke.getKeyStroke(
				            KeyEvent.VK_Y, ActionEvent.CTRL_MASK));
					jMenuItem.addActionListener(new ActionListener() {
						@Override
						public void actionPerformed(ActionEvent arg0) {
							if(currentEntry != null){
								currentEntry.noteRedoAction();
							}else{
								JOptionPane.showMessageDialog(new JFrame(),
										"Keine Notiz ausgewaehlt!", 
										"Hinweis",
										JOptionPane.INFORMATION_MESSAGE);
							}
						}
					});
					jMenu.add(jMenuItem);
					
					jMenu.addSeparator();
					
					jMenuItem = new JMenuItem("ausschneiden");
					jMenuItem.setIcon(res.cutIcon);
					jMenuItem.setAccelerator(KeyStroke.getKeyStroke(
				            KeyEvent.VK_X, ActionEvent.CTRL_MASK));
					jMenuItem.addActionListener(new ActionListener() {
						@Override
						public void actionPerformed(ActionEvent arg0) {
							if(currentEntry != null){
								currentEntry.noteCutAction();
							}else{
								JOptionPane.showMessageDialog(new JFrame(),
										"Keine Notiz ausgewaehlt!", 
										"Hinweis",
										JOptionPane.INFORMATION_MESSAGE);
							}
						}
					});
					jMenu.add(jMenuItem);
					
					jMenuItem = new JMenuItem("kopieren");
					jMenuItem.setIcon(res.copyIcon);
					jMenuItem.setAccelerator(KeyStroke.getKeyStroke(
				            KeyEvent.VK_C, ActionEvent.CTRL_MASK));
					jMenuItem.addActionListener(new ActionListener() {
						@Override
						public void actionPerformed(ActionEvent arg0) {
							if(currentEntry != null){
								currentEntry.noteCopyAction();
							}else{
								JOptionPane.showMessageDialog(new JFrame(),
										"Keine Notiz ausgewaehlt!", 
										"Hinweis",
										JOptionPane.INFORMATION_MESSAGE);
							}
						}
					});
					jMenu.add(jMenuItem);
					
					jMenuItem = new JMenuItem("einfuegen");
					jMenuItem.setIcon(res.pasteIcon);
					jMenuItem.setAccelerator(KeyStroke.getKeyStroke(
				            KeyEvent.VK_V, ActionEvent.CTRL_MASK));
					jMenuItem.addActionListener(new ActionListener() {
						@Override
						public void actionPerformed(ActionEvent arg0) {
							if(currentEntry != null){
								currentEntry.notePasteAction();
							}else{
								JOptionPane.showMessageDialog(new JFrame(),
										"Keine Notiz ausgewaehlt!", 
										"Hinweis",
										JOptionPane.INFORMATION_MESSAGE);
							}
						}
					});
					jMenu.add(jMenuItem);
					
					jMenu.addSeparator();
					
					jMenuItem = new JMenuItem("alles markieren");
					jMenuItem.setAccelerator(KeyStroke.getKeyStroke(
				            KeyEvent.VK_A, ActionEvent.CTRL_MASK));
					jMenuItem.addActionListener(new ActionListener() {
						@Override
						public void actionPerformed(ActionEvent arg0) {
							if(currentEntry != null){
								currentEntry.noteSelectAllAction();
							}else{
								JOptionPane.showMessageDialog(new JFrame(),
										"Keine Notiz ausgewaehlt!", 
										"Hinweis",
										JOptionPane.INFORMATION_MESSAGE);
							}
						}
					});
					jMenu.add(jMenuItem);
				}
				menuBar.add(jMenu);
			}
			{
				jMenu = new JMenu("Ansicht");
				{
					final JCheckBoxMenuItem jCheckBoxMenuItem  = 
						new JCheckBoxMenuItem ("Notiz-Einstellungen");
					jCheckBoxMenuItem.addActionListener(new ActionListener() {
						@Override
						public void actionPerformed(ActionEvent arg0) {
							if(currentEntry != null){
								jCheckBoxMenuItem.setSelected(
								currentEntry.showDetails());
							}else{
								JOptionPane.showMessageDialog(new JFrame(),
										"Keine Notiz ausgewaehlt!", 
										"Hinweis",
										JOptionPane.INFORMATION_MESSAGE);
							}
						}
					});
					jMenu.add(jCheckBoxMenuItem);
				}
				menuBar.add(jMenu);
			}
			{
				jMenu = new JMenu("Format");
				{
					jSubMenu = new JMenu("Formatvorlagen");
					jSubMenu.setEnabled(false);
					{
						jMenuItem = new JMenuItem("Ueberschrift 1");
						jMenuItem.addActionListener(new ActionListener() {
							@Override
							public void actionPerformed(ActionEvent arg0) {
								if(currentEntry != null){
									currentEntry.setHeadline(1);
								}else{
									JOptionPane.showMessageDialog(new JFrame(),
											"Keine Notiz ausgewaehlt!", 
											"Hinweis",
											JOptionPane.INFORMATION_MESSAGE);
								}
							}
						});
						jSubMenu.add(jMenuItem);
						
						jMenuItem = new JMenuItem("Ueberschrift 2");
						jMenuItem.addActionListener(new ActionListener() {
							@Override
							public void actionPerformed(ActionEvent arg0) {
								if(currentEntry != null){
									currentEntry.setHeadline(2);
								}else{
									JOptionPane.showMessageDialog(new JFrame(),
											"Keine Notiz ausgewaehlt!", 
											"Hinweis",
											JOptionPane.INFORMATION_MESSAGE);
								}
							}
						});
						jSubMenu.add(jMenuItem);
						
						jMenuItem = new JMenuItem("Ueberschrift 3");
						jMenuItem.addActionListener(new ActionListener() {
							@Override
							public void actionPerformed(ActionEvent arg0) {
								if(currentEntry != null){
									currentEntry.setHeadline(3);
								}else{
									JOptionPane.showMessageDialog(new JFrame(),
											"Keine Notiz ausgewaehlt!", 
											"Hinweis",
											JOptionPane.INFORMATION_MESSAGE);
								}
							}
						});
						jSubMenu.add(jMenuItem);
						
						jMenuItem = new JMenuItem("Ueberschrift 4");
						jMenuItem.addActionListener(new ActionListener() {
							@Override
							public void actionPerformed(ActionEvent arg0) {
								if(currentEntry != null){
									currentEntry.setHeadline(4);
								}else{
									JOptionPane.showMessageDialog(new JFrame(),
											"Keine Notiz ausgewaehlt!", 
											"Hinweis",
											JOptionPane.INFORMATION_MESSAGE);
								}
							}
						});
						jSubMenu.add(jMenuItem);
					}
					jMenu.add(jSubMenu);
					
					jMenuItem = new JMenuItem("Tabelle einfuegen");
					jMenuItem.setEnabled(false);
					jMenuItem.addActionListener(new ActionListener() {
						@Override
						public void actionPerformed(ActionEvent arg0) {
							if(currentEntry != null){
								//TODO create table fnc
								currentEntry.insertTable(5,4);
							}else{
								JOptionPane.showMessageDialog(new JFrame(),
										"Keine Notiz ausgewaehlt!", 
										"Hinweis",
										JOptionPane.INFORMATION_MESSAGE);
							}
						}
					});
					jMenu.add(jMenuItem);
					
					jMenuItem = new JMenuItem("Bild einfuegen");
					jMenuItem.addActionListener(new ActionListener() {
						@Override
						public void actionPerformed(ActionEvent arg0) {
							if(currentEntry != null){
								//TODO create table fnc
								currentEntry.setImage();
							}else{
								JOptionPane.showMessageDialog(new JFrame(),
										"Keine Notiz ausgewaehlt!", 
										"Hinweis",
										JOptionPane.INFORMATION_MESSAGE);
							}
						}
					});
					jMenu.add(jMenuItem);
					
					jMenu.addSeparator();
					
					jSubMenu = new JMenu("Text Style");
				    {
				    	jMenuItem = new JMenuItem("RTF (Standard)");
				    	jMenuItem.addActionListener(new ActionListener() {
				        	public void actionPerformed(ActionEvent evt) {
				        		if(currentEntry != null){
									currentEntry.setStyleType(TYPE.iRTF);
								}else{
									JOptionPane.showMessageDialog(new JFrame(),
											"Keine Notiz ausgewaehlt!", 
											"Hinweis",
											JOptionPane.INFORMATION_MESSAGE);
								}
				        	}
				        });		    
					    jSubMenu.add(jMenuItem);
					    
					    jMenuItem = new JMenuItem("JAVA");
					    jMenuItem.addActionListener(new ActionListener() {

							public void actionPerformed(ActionEvent evt) {
								if(currentEntry != null){
									currentEntry.setStyleType(TYPE.iJAVA);
								}else{
									JOptionPane.showMessageDialog(new JFrame(),
											"Keine Notiz ausgewaehlt!", 
											"Hinweis",
											JOptionPane.INFORMATION_MESSAGE);
								}
				        	}
				        });		    
					    jSubMenu.add(jMenuItem);
					    
					    jMenuItem = new JMenuItem("c/cpp");
					    jMenuItem.addActionListener(new ActionListener() {
				        	public void actionPerformed(ActionEvent evt) {
				        		if(currentEntry != null){
									currentEntry.setStyleType(TYPE.iCPP);
								}else{
									JOptionPane.showMessageDialog(new JFrame(),
											"Keine Notiz ausgewaehlt!", 
											"Hinweis",
											JOptionPane.INFORMATION_MESSAGE);
								}
				        	}
				        });		    
					    jSubMenu.add(jMenuItem);
					    
					    jMenuItem = new JMenuItem("HTML");
					    jMenuItem.addActionListener(new ActionListener() {
				        	public void actionPerformed(ActionEvent evt) {
				        		if(currentEntry != null){
									currentEntry.setStyleType(TYPE.iHTML);
								}else{
									JOptionPane.showMessageDialog(new JFrame(),
											"Keine Notiz ausgewaehlt!", 
											"Hinweis",
											JOptionPane.INFORMATION_MESSAGE);
								}
				        	}
				        });		    
					    jSubMenu.add(jMenuItem);
					    
					    jMenuItem = new JMenuItem("JAVASCRIPT");
					    jMenuItem.addActionListener(new ActionListener() {
				        	public void actionPerformed(ActionEvent evt) {
				        		if(currentEntry != null){
									currentEntry.setStyleType(TYPE.iJS);
								}else{
									JOptionPane.showMessageDialog(new JFrame(),
											"Keine Notiz ausgewaehlt!", 
											"Hinweis",
											JOptionPane.INFORMATION_MESSAGE);
								}
				        	}
				        });		    
					    jSubMenu.add(jMenuItem);
					    
					    jMenuItem = new JMenuItem("SQL");
					    jMenuItem.addActionListener(new ActionListener() {
				        	public void actionPerformed(ActionEvent evt) {
				        		if(currentEntry != null){
									currentEntry.setStyleType(TYPE.iSQL);
								}else{
									JOptionPane.showMessageDialog(new JFrame(),
											"Keine Notiz ausgewaehlt!", 
											"Hinweis",
											JOptionPane.INFORMATION_MESSAGE);
								}
				        	}
				        });		    
					    jSubMenu.add(jMenuItem);
					    
					    jMenuItem = new JMenuItem("(La)TeX");
					    jMenuItem.addActionListener(new ActionListener() {
				        	public void actionPerformed(ActionEvent evt) {
				        		if(currentEntry != null){
									currentEntry.setStyleType(TYPE.iTeX);
								}else{
									JOptionPane.showMessageDialog(new JFrame(),
											"Keine Notiz ausgewaehlt!", 
											"Hinweis",
											JOptionPane.INFORMATION_MESSAGE);
								}
				        	}
				        });		    
					    jSubMenu.add(jMenuItem);
				    }
				    jMenu.add(jSubMenu);

					
					jMenu.addSeparator();
					
					jMenuItem = new JMenuItem("alle Formatierungen loeschen");
					jMenuItem.addActionListener(new ActionListener() {
						@Override
						public void actionPerformed(ActionEvent arg0) {
							if(currentEntry != null){
								currentEntry.noteClearFormat();
							}else{
								JOptionPane.showMessageDialog(new JFrame(),
										"Keine Notiz ausgewaehlt!", 
										"Hinweis",
										JOptionPane.INFORMATION_MESSAGE);
							}
						}
					});
					jMenu.add(jMenuItem);
				}
				menuBar.add(jMenu);
			}
			{
				jMenu = new JMenu("Extras");
				{
					jMenuItem = new JMenuItem("als Email senden");
					jMenuItem.setEnabled(false);
					jMenuItem.addActionListener(new ActionListener() {
			        	public void actionPerformed(ActionEvent evt) {
			        		if(currentEntry != null){
								//TODO
							}else{
								JOptionPane.showMessageDialog(new JFrame(),
										"Keine Notiz ausgewaehlt!", 
										"Hinweis",
										JOptionPane.INFORMATION_MESSAGE);
							}
				        }
				    });		    
				    jMenu.add(jMenuItem);
				    
					jMenuItem = new JMenuItem("N2G Einstellungen");
					jMenuItem.addActionListener(new ActionListener() {
			        	public void actionPerformed(ActionEvent evt) {
			        		mainPane.add(getPrefPanel(), "card-113");
							labelTree.expandRow(0);
							showCard(-113);
							labelTree.select(lOption);
				        }
				    });		    
				    jMenu.add(jMenuItem);
				}
				menuBar.add(jMenu);
			}
			{
				jMenu = new JMenu("Hilfe");
				jMenu.setEnabled(false);
				{
					jMenuItem = new JMenuItem("Updates suchen");
					jMenuItem.addActionListener(new ActionListener() {
						@Override
						public void actionPerformed(ActionEvent arg0) {
							//TODO search update
						}
					});
					jMenu.add(jMenuItem);
					
					jMenuItem = new JMenuItem("Kleine Einfuehrung");
					jMenuItem.addActionListener(new ActionListener() {
						@Override
						public void actionPerformed(ActionEvent arg0) {
							//TODO getting started
						}
					});
					jMenu.add(jMenuItem);
					
					jMenuItem = new JMenuItem("Ueber Note2Go");
					jMenuItem.addActionListener(new ActionListener() {
						@Override
						public void actionPerformed(ActionEvent arg0) {
							//TODO about n2g
						}
					});
					jMenu.add(jMenuItem);
				}
				menuBar.add(jMenu);
			}
		}
		return menuBar;
	}
	
	private JPanel getPrefPanel(){
		if(pref == null){
			final Options iOptions;
			pref = new JPanel(new BorderLayout());
			{
				iOptions = new Options();
				iOptions.setOptionPanel(options);
				pref.add(iOptions, BorderLayout.CENTER);
			}
			{
				JPanel btnPanel = new JPanel();
				JButton btnOption;
				btnOption = new JButton("Speichern");
				btnOption.addActionListener(new ActionListener() {
					@Override
					public void actionPerformed(ActionEvent e) {
						setNewPrefs(iOptions.getOptionsSet());
						mainPane.remove(pref);
						((LabelModel) labelTree.getModel()).removeChild(common, lOption);
						labelTree.select(lHome);
						labelTree.expandRow(0);
						pref = null;
					}
				});
				btnPanel.add(btnOption);
				
				btnOption = new JButton("Abbrechen");
				btnOption.addActionListener(new ActionListener() {
					@Override
					public void actionPerformed(ActionEvent e) {
						Object[] options = {"Ja, bitte","Nein, bitte jetzt speichern"};
						int n = JOptionPane.showOptionDialog(new JFrame(),
						    "Aenderungen der Einstellungen werden nicht gespeichert.\n"
						    + "Sollen die Aenderungen verworfen werden?",
						    "Hinweis",
						    JOptionPane.YES_NO_CANCEL_OPTION,
						    JOptionPane.QUESTION_MESSAGE,
						    null,options,options[0]);
						if(n == 1){
							setNewPrefs(iOptions.getOptionsSet());
						}
						mainPane.remove(pref);
						((LabelModel) labelTree.getModel()).removeChild(common, lOption);
						labelTree.select(lHome);
						labelTree.expandRow(0);
						pref = null;
					}
				});
				btnPanel.add(btnOption);
//				box.add(Box.createVerticalGlue());
//				box.add(Box.createHorizontalGlue());
//				Box.Filler filler = new Filler(new Dimension(10,10), new Dimension(Short.MAX_VALUE, Short.MAX_VALUE), new Dimension(Short.MAX_VALUE, Short.MAX_VALUE));
////				box.add(Box.createVerticalStrut(10,Short.MAX_VALUE));
//				box.add(filler);
//				box.add(btnPanel);
//				pref.add(box, BorderLayout.CENTER);
				pref.add(btnPanel, BorderLayout.PAGE_END);
			}
			
			((LabelModel) labelTree.getModel()).addChild(common, lOption);
		}
		return pref;
	}
	
	private void setNewPrefs(OptionsSet optionsSet){
		if(iDB.setOptions(optionsSet)){
			this.options = optionsSet;
			setStatusText();
		}
	}
	
	private void saveNote(){
		if(currentEntry != null){
			Label temp = currLabel;
			EntrySet es = iDB.setEntry(currentEntry.getEntrySet());
			setAllTags();
			
			for (Component comp : mainPane.getComponents()) {
				if(comp.getName() != null && comp.getName().matches("ientry")){
					((Entry) comp).setCommonLabelList(allTagList);
				}
			}
			
			if(temp.isNewNote()){
				closeNote();
				setEntryDetail(es.getEntryID());
			}else{
				currentEntry.setEntrySet(es);			
				temp.setName(es.getEntryTitle());
				temp.setToolTip(es.getEntryTitle());
			}
			((LabelModel) labelTree.getModel()).removeAllChildren(all);
			((LabelModel) labelTree.getModel()).addAllChildren(all, allTagListNumbered);
			labelTree.expandRow(0);
			labelTree.expandRow(1);
			labelTree.expandRow(2);
			
			labelTree.select(temp);
		}else{
			JOptionPane.showMessageDialog(new JFrame(),
					"Keine Notiz ausgewaehlt!", 
					"Hinweis",
					JOptionPane.INFORMATION_MESSAGE);
		}

	}
	
	private void closeNote(){
		if(currentEntry != null){
			mainPane.remove(currentEntry);
			Label label = (Label) labelTree.getLastSelectedPathComponent();
			((LabelModel) labelTree.getModel()).removeChild(used, label);
			labelTree.select(lHome);
			labelTree.expandRow(0);
		}else{
			JOptionPane.showMessageDialog(new JFrame(),
					"Keine Notiz ausgewaehlt!", 
					"Hinweis",
					JOptionPane.INFORMATION_MESSAGE);
		}
	}

	private void deleteNote(){
		if(currentEntry != null){
			mainPane.remove(currentEntry);
			Label label = (Label) labelTree.getLastSelectedPathComponent();
			((LabelModel) labelTree.getModel()).removeChild(used, label);
			iDB.deleteEntry(label.getLabelID());
			labelTree.select(lHome);
			labelTree.expandRow(0);
		}else{
			JOptionPane.showMessageDialog(new JFrame(),
					"Keine Notiz ausgewaehlt!", 
					"Hinweis",
					JOptionPane.INFORMATION_MESSAGE);
		}
	}

}
